﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Serialization;
using NASA.BeAMartian.Controls.Images;
using NASA.BeAMartian.Model;
using System.Windows.Navigation;
using Microsoft.Phone.Shell;
using System.Xml;
using System.IO;
using NASA.BeAMartian.Controls;

namespace NASA.BeAMartian.Views
{
    public partial class ViewImage : PhoneApplicationPage
    {
        Image activeImage;
        List<Image> images = new List<Image>();

        public ViewImage()
        {
            InitializeComponent();    
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //if navigating directly from landing page, then load the image catalog first
            if (NavigationContext.QueryString.ContainsKey("sel"))
            {
                string url = String.Format("http://beamdownload.blob.core.windows.net/media/WP7/marsgallery/{0}.xml", NavigationContext.QueryString["x"]);
                WebClient xmlClient = new WebClient();
                xmlClient.Headers["galleryName"] = NavigationContext.QueryString["x"];
                xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(xmlClient_DownloadStringCompleted);
                xmlClient.DownloadStringAsync(new Uri(url, UriKind.Absolute));
            }
            else
                loadImage();

            base.OnNavigatedTo(e);
        }

        void xmlClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                string uri = ((System.Net.WebClient)(sender)).BaseAddress.ToString();

                XmlSerializer x = new XmlSerializer(typeof(ImageGallery));

                using (XmlReader reader = XmlReader.Create(new StringReader(e.Result)))
                {
                    string galleryName = (sender as WebClient).Headers["galleryName"];
                    ImageGallery ig = (ImageGallery)x.Deserialize(reader);

                    ImageGalleryItem igi =
                        (from n in ig
                         where n.ImageID == NavigationContext.QueryString["sel"]
                         select n).FirstOrDefault();

                    ApplicationContext.Instance.ImageGalleryData = ig;
                    ApplicationContext.Instance.ImageGalleryItemData = igi;
                    loadImage();
                }
            }
        }

        void loadImage()
        {
            pvtPhotos.ItemsSource = ApplicationContext.Instance.ImageGalleryData;
            ImageGalleryItem igi = ApplicationContext.Instance.ImageGalleryItemData;
            DataContext = igi;
            pvtPhotos.SelectedItem = ApplicationContext.Instance.ImageGalleryItemData;
            images.Clear();
        }

        void setRowVisibility(StackPanel sp, string property)
        {
            sp.Visibility = String.IsNullOrEmpty(property) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
        }

        void imgPhoto_ImageOpened(object sender, RoutedEventArgs e)
        {
            Image img = sender as Image;
            images.Add(img);

            activeImage =
                (from n in images
                 where n.Tag.ToString() == ((ImageGalleryItem)DataContext).Title
                 select n).FirstOrDefault();

            Grid parentGrid = Utils.VisualTreeUtils.FindParentByType<Grid>(img);
            StackPanel spContainer = Utils.VisualTreeUtils.FindParentByType<StackPanel>(img);
            ProgressBar pbLoading = parentGrid.Children[0] as ProgressBar;
            pbLoading.IsIndeterminate = false;
            pbLoading.Visibility = System.Windows.Visibility.Collapsed;

            //Fade in image.           
            Storyboard sbFadeInImage = new Storyboard();
            Duration duration = new Duration(TimeSpan.FromMilliseconds(500));
            DoubleAnimation dblAnimation = new DoubleAnimation();
            dblAnimation.Duration = duration;
            Storyboard.SetTarget(dblAnimation, spContainer);
            Storyboard.SetTargetProperty(dblAnimation, new PropertyPath("(UIElement.Opacity)"));
            dblAnimation.To = 1;
            sbFadeInImage.Children.Add(dblAnimation);
            sbFadeInImage.Begin();
        }

        private void abPrevious_Click(object sender, EventArgs e)
        {
            ImageGalleryItem igi = DataContext as ImageGalleryItem;
            if (pvtPhotos.SelectedIndex == 0)
                pvtPhotos.SelectedIndex = pvtPhotos.Items.Count - 1;
            else
                pvtPhotos.SelectedIndex -= 1;
        }

        private void abNext_Click(object sender, EventArgs e)
        {
            ImageGalleryItem igi = DataContext as ImageGalleryItem;
            if (pvtPhotos.SelectedIndex == pvtPhotos.Items.Count - 1)
                pvtPhotos.SelectedIndex = 0;
            else
                pvtPhotos.SelectedIndex += 1;
        }

        private void abMarsTopTen_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Views/MarsGallery/MarsGallery.xaml?x=0", UriKind.Relative));
        }

        private void abMarsAsArt_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Views/MarsGallery/MarsGallery.xaml?x=1", UriKind.Relative));
        }

        private void abBeAMHome_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Welcome.xaml", UriKind.Relative));
        }

        private void tbComments_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            string val = tb.Tag.ToString();

            //Buffer comments line to make room for an inline label.
            tb.Text = "                  " + val;

            tb_Loaded(tb, e);
        }

        private void tb_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            StackPanel spContainter = Utils.VisualTreeUtils.FindParentByType<StackPanel>(tb);
            setRowVisibility(spContainter, tb.Text.Trim());
        }

        private void imgPhoto_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
        }

        private void abZoomIn_Click(object sender, EventArgs e)
        {
            pvtPhotos.Opacity = 0;
            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = true;
            (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = false;
            imgLandscape.Source = activeImage.Source;
            imgPortrait.Source = activeImage.Source;

            if (activeImage.ActualWidth > activeImage.ActualHeight)
                imgLandscape.Visibility = System.Windows.Visibility.Visible;
            else
                imgPortrait.Visibility = System.Windows.Visibility.Visible;
        }

        private void abZoomOut_Click(object sender, EventArgs e)
        {
            resetAppBar();
        }

        private void pvtPhotos_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            resetAppBar();

            DataContext = e.AddedItems[0] as ImageGalleryItem;

            activeImage =
                (from n in images
                 where n.Tag.ToString() == ((ImageGalleryItem)DataContext).Title
                 select n).FirstOrDefault();
        }

        void resetAppBar()
        {
            pvtPhotos.Opacity = 1.0;
            imgLandscape.Visibility = System.Windows.Visibility.Collapsed;
            imgPortrait.Visibility = System.Windows.Visibility.Collapsed;
            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
            (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = true;
        }

    }
}